<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键词">
                <a-input v-model="queryParam.username" placeholder="请输入登录账户" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button type="primary" icon="plus" @click="onAdd()">新建</a-button>
      </div>
      <s-table
        :row-key="
          (r, i) => {
            return i
          }
        "
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <span slot="status" slot-scope="text, record">
          <template>
            <a-switch
              :checked="text | statusFilter"
              checked-children="开"
              un-checked-children="关"
              @change="changeStatus($event, record.id)"
            ></a-switch>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
            <a-button type="link" @click="handleEditPassword(record)" size="small">修改密码</a-button>
            <a-divider type="vertical" />
            <a-popconfirm title="确认删除该信息吗？" @confirm="handleDelete(record)">
              <a-button type="link" size="small">删除</a-button>
            </a-popconfirm>
          </template>
        </span>
      </s-table>
      <a-modal
        title="修改密码"
        :visible="setPwd"
        :confirm-loading="confirmLoading"
        @ok="setPasswordOk"
        @cancel="setPwd = false"
      >
        <a-form-model
          ref="form"
          :model="pwd"
          :rules="formPwdRules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <a-form-item prop="name" label="登录密码">
            <a-input placeholder="请输入登录密码" v-model="pwd.password"></a-input>
          </a-form-item>
        </a-form-model>

      </a-modal>
      <a-modal
        :title="form.id ? '编辑管理员' : '新增管理员'"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="visible = false"
      >
        <a-form-model
          ref="form"
          :model="form"
          :rules="formRules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <a-form-item prop="name" label="登录账户">
            <a-input placeholder="请输入登录账户" v-model="form.username"></a-input>
          </a-form-item>
          <a-form-item prop="name" label="登录密码" v-if='!form.id'>
            <a-input placeholder="请输入登录密码" v-model="form.password"></a-input>
          </a-form-item>
          <a-form-item prop="name" label="是否启用">
            <a-radio-group name="radioGroup" v-model="form.status" :default-value="0">
              <a-radio :value="1"> 开启 </a-radio>
              <a-radio :value="0"> 关闭 </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="权限控制" v-if="form.rules.length > 0">
            <a-tree
              :treeData="form.rules"
              :checkable="true"
              :selectable="true"
              :defaultSelectedKeys="store_rules"
              v-model='store_rules'
              @check="onTreeCheck"
            ></a-tree>
          </a-form-item>
        </a-form-model>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { getAdminList, getInfo, save, setPassword, setStatus, del } from '@/api/storeAdmin'
import pt from '@/api/pt'
const STATUS = {
  0: false,
  1: true,
}
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '登录账户',
    dataIndex: 'username',
  },
  // {
  //   title: '返佣比例(‰)',
  //   dataIndex: 'fybili',
  // },
  {
    title: '创建时间',
    dataIndex: 'created_at',
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'RechargeList',
  components: {
    STable,
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      // form: this.$form.createForm(this),
      form: {
        username: '',
        password: '',
        id: 0,
        rules: '',
        status: 0
      },
      // 表头
      columns,
      image: null,
      selectRadio: null,
      records: {},
      isNew: false,
      selectedLevel: String,
      // 权限树
      permissionTree: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return getAdminList(parameter).then((res) => {

          return res.data
        })
      },
      queryParam: {},
      formRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入账户名称' }],
        password: [{ required: true, trigger: 'blur', message: '请输入账户密码' }],
      },
      formPwdRules: {
        password: [{ required: true, trigger: 'blur', message: '请输入账户密码' }],
      },
      store_rules: [],
      setPwd: false,
      pwd: {
        id: 0,
        password: ''
      }
    }
  },
  created() {},
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  methods: {
    onTreeCheck: function (checkedKeys, info) {
      this.store_rules = checkedKeys
    },
    resetSearchForm() {
      this.queryParam = {}
    },
    changeStatus: function (value, id) {
      const status = Object.keys(STATUS).find((key) => STATUS[key] === value)
      console.log('status', status);
      var params = {
        id: id,
        status: status,
      }
      this.modalLoading = true
      setStatus(params).then((res) => {
        this.modalLoading = false
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$refs.table.refresh()
          this.$message.success('更新成功！')
        }
      })
    },
    async handleOk(e) {
      let form = this.form
      this.confirmLoading = true
      form.store_rules = this.store_rules.join(',')
      const res = await save(form)
      if (res.code === 0) {
        this.visible = false
        this.$refs.table.refresh()
      }
      this.confirmLoading = false

    },
    async handleEdit(record) {
      this.confirmLoading = true
      let id = record.id;
      const res = await getInfo({id: id});
      if (res.code === 0) {
        this.visible = true
        this.form = res.data
        this.store_rules = res.data.store_rules
        this.$refs.table.refresh()
      }
      this.confirmLoading = false
    },

    handleEditPassword(record) {
      this.setPwd = true;
      // this.confirmLoading = true
      this.pwd.id = record.id;
      console.log(this.pwd);
    },

    async setPasswordOk() {
      let pwd = this.pwd;
      this.confirmLoading = true;
      const res = await setPassword(pwd);
      if (res.code === 0) {
        this.confirmLoading = false
        this.setPwd = false;
        this.pwd = {
          id: 0,
          password: ''
        };
        this.$refs.table.refresh()
      }
    },

    async onAdd() {
      const res = await getInfo();
      if (res.code === 0) {
        this.visible = true
        this.form = res.data
        this.store_rules = [];
        this.confirmLoading = false
      }
    },
    handleDelete: function (record) {
      del({
        id: record.id,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    radioChange(e) {
      this.selectRadio = e.target.value
    },
    levelChange(value) {
      this.selectedLevel = value
    },
    onOk(val) {
      this.image = val
    },
    addSynopsis() {
      this.records.synopsis.push({
        title: '',
        content: '',
        pic: '',
      })
    },
    del(e, record, index) {
      this.records.synopsis.splice(index, 1)
    },
  },
}
</script>
